// routes/pay.js
const Router = require('koa-router');
const crypto = require('crypto');
const axios = require('axios');
const router = new Router({ prefix: '/api/pay' });
const xml2js = require('xml2js');
const config = {
  appid: 'wx37b8a3060ce84f6a',
  mch_id: '1720005310',
  key: '20250623sclmjtwhcbyxgs0000000001',
  notify_url: 'https://localhost:3000/api/pay/notify'
};

// 工具函数：生成签名
function createSign(params, key) {
  const string = Object.keys(params)
    .sort()
    .map(k => `${k}=${params[k]}`)
    .join('&') + `&key=${key}`;

  return crypto.createHash('md5').update(string, 'utf8').digest('hex').toUpperCase();
}

// 生成 XML
function jsonToXml(obj) {
  let xml = `<xml>`;
  for (let key in obj) {
    xml += `<${key}><![CDATA[${obj[key]}]]></${key}>`;
  }
  xml += `</xml>`;
  return xml;
}

// 解析 XML（简单方式）

function parseXml(xml) {
  return new Promise((resolve, reject) => {
    xml2js.parseString(xml, { explicitArray: false }, (err, result) => {
      if (err) reject(err);
      else resolve(result.xml);
    });
  });
}

// 下单接口
router.post('/unifiedOrder', async (ctx) => {
  const { openid, out_trade_no, total_fee, body } = ctx.request.body;

  const params = {
    appid: config.appid,
    mch_id: config.mch_id,
    nonce_str: Math.random().toString(36).substr(2, 15),
    body,
    out_trade_no,
    total_fee, // 单位：分
    spbill_create_ip: ctx.ip.replace('::ffff:', ''),
    notify_url: config.notify_url,
    trade_type: 'JSAPI',
    openid
  };

  params.sign = createSign(params, config.key);

  const xml = jsonToXml(params);

  const response = await axios.post('https://api.mch.weixin.qq.com/pay/unifiedorder', xml, {
    headers: { 'Content-Type': 'text/xml' }
  });

  const result = await parseXml(response.data);
console.log(result,'result');

  if (result.return_code === 'SUCCESS' && result.result_code === 'SUCCESS') {
    const paySignParams = {
      appId: config.appid,
      timeStamp: `${Math.floor(Date.now() / 1000)}`,
      nonceStr: params.nonce_str,
      package: `prepay_id=${result.prepay_id}`,
      signType: 'MD5',
    };
    paySignParams.paySign = createSign(paySignParams, config.key);

    ctx.body = {
      code: 200,
      data: paySignParams
    };
  } else {
    ctx.body = {
      code: 500,
      message: result.return_msg || '微信下单失败',
      detail: result
    };
  }
});
router.post('/notify', async (ctx) => {
  const xmlData = ctx.request.rawBody;
  const result = await parseXml(xmlData);

  const { sign, ...rest } = result;
  const validSign = createSign(rest, config.key);

  if (validSign === sign && result.result_code === 'SUCCESS') {
    // 更新订单状态
    await db.query('UPDATE orders SET status = ? WHERE order_no = ?', ['已支付', result.out_trade_no]);

    ctx.body = `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
  } else {
    ctx.body = `<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名错误]]></return_msg></xml>`;
  }
});

module.exports = router;